import Vue from 'vue'
import Vuex from 'vuex'

// 1.安装插件

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    cartList: []
  },
  mutations: {
    addCart(state, goods) {
      state.cartList.push(goods)
    },
    addCount(state, index) {
      state.cartList[index].count += 1
    }
  },
  getters: {
    cartLength(state) {
      return state.cartList.length
    },
    cartList(state) {
      return state.cartList
    }
  },
  actions:{
    addToCart({state, commit}, info) {
      return new Promise((resolve) => {
        // 1.查看该商品是否已经添加到cartList中
        const oldInfo = state.cartList.find(item => item.iid === info.iid)

        // 2.如果oldInfo存在, 那么原来的数量加1
        if (oldInfo) {
          const index = state.cartList.indexOf(oldInfo)
          commit('addCount', index)
          resolve('商品数量+1')
        } else {
          info.count = 1
          info.checked = true
          commit('addCart', info)
          resolve('商品种类+1')
        }
      })
    }
  }

})

export default store